/**
 * @author: qwesde@hust.edu.cn
 * @date: 2021/2/10 23:20
 */
import {asyncRouterMap, constantRouterMap} from "../../router";
import {SET_ROUTERS} from "../EventConstant";

const permission = {
    state: {
        routers: constantRouterMap,
        addRouters: [],
    },
    mutations: {
        [SET_ROUTERS]: (state, routers) => {
            state.addRouters = routers;
            state.routers = constantRouterMap.concat(routers);
        }
    },
    actions: {
        GenerateRouters({ commit }, data) {
            return new Promise(resolve => {
                const { menus } = data;
                let map = {}; // hash 方便o(1)查找
                menus.forEach(item => {
                    map[item.path] = 1;
                });
                const okRouters = asyncRouterMap.filter(item => {
                    // url: /admin
                    if (map[item.path]) {
                        if(item.child) {
                            item.children = item.children.filter(subItem => {
                                // url: /admin/index
                                return !!(map[item.path + '/' + subItem.path])
                            })
                        }
                        return true;
                    }
                    return false;
                });
                commit(SET_ROUTERS, okRouters);
                resolve();
            })
        }
    }
}

export default permission;